home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / distutils / ccompiler.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  39KB  |  984 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''distutils.ccompiler
  5.  
  6. Contains CCompiler, an abstract base class that defines the interface
  7. for the Distutils compiler abstraction model.'''
  8. __revision__ = '$Id: ccompiler.py 67896 2008-12-21 17:01:26Z benjamin.peterson $'
  9. import sys
  10. import os
  11. import re
  12. from types import *
  13. from copy import copy
  14. from distutils.errors import *
  15. from distutils.spawn import spawn
  16. from distutils.file_util import move_file
  17. from distutils.dir_util import mkpath
  18. from distutils.dep_util import newer_pairwise, newer_group
  19. from distutils.util import split_quoted, execute
  20. from distutils import log
  21.  
  22. class CCompiler:
  23.     '''Abstract base class to define the interface that must be implemented
  24.     by real compiler classes.  Also has some utility methods used by
  25.     several compiler classes.
  26.  
  27.     The basic idea behind a compiler abstraction class is that each
  28.     instance can be used for all the compile/link steps in building a
  29.     single project.  Thus, attributes common to all of those compile and
  30.     link steps -- include directories, macros to define, libraries to link
  31.     against, etc. -- are attributes of the compiler instance.  To allow for
  32.     variability in how individual files are treated, most of those
  33.     attributes may be varied on a per-compilation or per-link basis.
  34.     '''
  35.     compiler_type = None
  36.     src_extensions = None
  37.     obj_extension = None
  38.     static_lib_extension = None
  39.     shared_lib_extension = None
  40.     static_lib_format = None
  41.     shared_lib_format = None
  42.     exe_extension = None
  43.     language_map = {
  44.         '.c': 'c',
  45.         '.cc': 'c++',
  46.         '.cpp': 'c++',
  47.         '.cxx': 'c++',
  48.         '.m': 'objc' }
  49.     language_order = [
  50.         'c++',
  51.         'objc',
  52.         'c']
  53.     
  54.     def __init__(self, verbose = 0, dry_run = 0, force = 0):
  55.         self.dry_run = dry_run
  56.         self.force = force
  57.         self.verbose = verbose
  58.         self.output_dir = None
  59.         self.macros = []
  60.         self.include_dirs = []
  61.         self.libraries = []
  62.         self.library_dirs = []
  63.         self.runtime_library_dirs = []
  64.         self.objects = []
  65.         for key in self.executables.keys():
  66.             self.set_executable(key, self.executables[key])
  67.         
  68.  
  69.     
  70.     def set_executables(self, **args):
  71.         """Define the executables (and options for them) that will be run
  72.         to perform the various stages of compilation.  The exact set of
  73.         executables that may be specified here depends on the compiler
  74.         class (via the 'executables' class attribute), but most will have:
  75.           compiler      the C/C++ compiler
  76.           linker_so     linker used to create shared objects and libraries
  77.           linker_exe    linker used to create binary executables
  78.           archiver      static library creator
  79.  
  80.         On platforms with a command-line (Unix, DOS/Windows), each of these
  81.         is a string that will be split into executable name and (optional)
  82.         list of arguments.  (Splitting the string is done similarly to how
  83.         Unix shells operate: words are delimited by spaces, but quotes and
  84.         backslashes can override this.  See
  85.         'distutils.util.split_quoted()'.)
  86.         """
  87.         for key in args.keys():
  88.             if key not in self.executables:
  89.                 raise ValueError, "unknown executable '%s' for class %s" % (key, self.__class__.__name__)
  90.             key not in self.executables
  91.             self.set_executable(key, args[key])
  92.         
  93.  
  94.     
  95.     def set_executable(self, key, value):
  96.         if type(value) is StringType:
  97.             setattr(self, key, split_quoted(value))
  98.         else:
  99.             setattr(self, key, value)
  100.  
  101.     
  102.     def _find_macro(self, name):
  103.         i = 0
  104.         for defn in self.macros:
  105.             if defn[0] == name:
  106.                 return i
  107.             i = i + 1
  108.         
  109.  
  110.     
  111.     def _check_macro_definitions(self, definitions):
  112.         """Ensures that every element of 'definitions' is a valid macro
  113.         definition, ie. either (name,value) 2-tuple or a (name,) tuple.  Do
  114.         nothing if all definitions are OK, raise TypeError otherwise.
  115.         """
  116.         for defn in definitions:
  117.             if type(defn) is TupleType:
  118.                 if len(defn) == 1 or len(defn) == 2:
  119.                     if not (type(defn[1]) is StringType or defn[1] is None) and type(defn[0]) is StringType:
  120.                         raise TypeError, "invalid macro definition '%s': " % defn + 'must be tuple (string,), (string, string), or ' + '(string, None)'
  121.                     type(defn[0]) is StringType
  122.                 return None
  123.  
  124.     
  125.     def define_macro(self, name, value = None):
  126.         """Define a preprocessor macro for all compilations driven by this
  127.         compiler object.  The optional parameter 'value' should be a
  128.         string; if it is not supplied, then the macro will be defined
  129.         without an explicit value and the exact outcome depends on the
  130.         compiler used (XXX true? does ANSI say anything about this?)
  131.         """
  132.         i = self._find_macro(name)
  133.         if i is not None:
  134.             del self.macros[i]
  135.         
  136.         defn = (name, value)
  137.         self.macros.append(defn)
  138.  
  139.     
  140.     def undefine_macro(self, name):
  141.         """Undefine a preprocessor macro for all compilations driven by
  142.         this compiler object.  If the same macro is defined by
  143.         'define_macro()' and undefined by 'undefine_macro()' the last call
  144.         takes precedence (including multiple redefinitions or
  145.         undefinitions).  If the macro is redefined/undefined on a
  146.         per-compilation basis (ie. in the call to 'compile()'), then that
  147.         takes precedence.
  148.         """
  149.         i = self._find_macro(name)
  150.         if i is not None:
  151.             del self.macros[i]
  152.         
  153.         undefn = (name,)
  154.         self.macros.append(undefn)
  155.  
  156.     
  157.     def add_include_dir(self, dir):
  158.         """Add 'dir' to the list of directories that will be searched for
  159.         header files.  The compiler is instructed to search directories in
  160.         the order in which they are supplied by successive calls to
  161.         'add_include_dir()'.
  162.         """
  163.         self.include_dirs.append(dir)
  164.  
  165.     
  166.     def set_include_dirs(self, dirs):
  167.         """Set the list of directories that will be searched to 'dirs' (a
  168.         list of strings).  Overrides any preceding calls to
  169.         'add_include_dir()'; subsequence calls to 'add_include_dir()' add
  170.         to the list passed to 'set_include_dirs()'.  This does not affect
  171.         any list of standard include directories that the compiler may
  172.         search by default.
  173.         """
  174.         self.include_dirs = copy(dirs)
  175.  
  176.     
  177.     def add_library(self, libname):
  178.         """Add 'libname' to the list of libraries that will be included in
  179.         all links driven by this compiler object.  Note that 'libname'
  180.         should *not* be the name of a file containing a library, but the
  181.         name of the library itself: the actual filename will be inferred by
  182.         the linker, the compiler, or the compiler class (depending on the
  183.         platform).
  184.  
  185.         The linker will be instructed to link against libraries in the
  186.         order they were supplied to 'add_library()' and/or
  187.         'set_libraries()'.  It is perfectly valid to duplicate library
  188.         names; the linker will be instructed to link against libraries as
  189.         many times as they are mentioned.
  190.         """
  191.         self.libraries.append(libname)
  192.  
  193.     
  194.     def set_libraries(self, libnames):
  195.         """Set the list of libraries to be included in all links driven by
  196.         this compiler object to 'libnames' (a list of strings).  This does
  197.         not affect any standard system libraries that the linker may
  198.         include by default.
  199.         """
  200.         self.libraries = copy(libnames)
  201.  
  202.     
  203.     def add_library_dir(self, dir):
  204.         """Add 'dir' to the list of directories that will be searched for
  205.         libraries specified to 'add_library()' and 'set_libraries()'.  The
  206.         linker will be instructed to search for libraries in the order they
  207.         are supplied to 'add_library_dir()' and/or 'set_library_dirs()'.
  208.         """
  209.         self.library_dirs.append(dir)
  210.  
  211.     
  212.     def set_library_dirs(self, dirs):
  213.         """Set the list of library search directories to 'dirs' (a list of
  214.         strings).  This does not affect any standard library search path
  215.         that the linker may search by default.
  216.         """
  217.         self.library_dirs = copy(dirs)
  218.  
  219.     
  220.     def add_runtime_library_dir(self, dir):
  221.         """Add 'dir' to the list of directories that will be searched for
  222.         shared libraries at runtime.
  223.         """
  224.         self.runtime_library_dirs.append(dir)
  225.  
  226.     
  227.     def set_runtime_library_dirs(self, dirs):
  228.         """Set the list of directories to search for shared libraries at
  229.         runtime to 'dirs' (a list of strings).  This does not affect any
  230.         standard search path that the runtime linker may search by
  231.         default.
  232.         """
  233.         self.runtime_library_dirs = copy(dirs)
  234.  
  235.     
  236.     def add_link_object(self, object):
  237.         '''Add \'object\' to the list of object files (or analogues, such as
  238.         explicitly named library files or the output of "resource
  239.         compilers") to be included in every link driven by this compiler
  240.         object.
  241.         '''
  242.         self.objects.append(object)
  243.  
  244.     
  245.     def set_link_objects(self, objects):
  246.         """Set the list of object files (or analogues) to be included in
  247.         every link to 'objects'.  This does not affect any standard object
  248.         files that the linker may include by default (such as system
  249.         libraries).
  250.         """
  251.         self.objects = copy(objects)
  252.  
  253.     
  254.     def _setup_compile(self, outdir, macros, incdirs, sources, depends, extra):
  255.         '''Process arguments and decide which source files to compile.
  256.  
  257.         Merges _fix_compile_args() and _prep_compile().
  258.         '''
  259.         if outdir is None:
  260.             outdir = self.output_dir
  261.         elif type(outdir) is not StringType:
  262.             raise TypeError, "'output_dir' must be a string or None"
  263.         
  264.         if macros is None:
  265.             macros = self.macros
  266.         elif type(macros) is ListType:
  267.             if not self.macros:
  268.                 pass
  269.             macros = macros + []
  270.         else:
  271.             raise TypeError, "'macros' (if supplied) must be a list of tuples"
  272.         if macros is None is None:
  273.             incdirs = self.include_dirs
  274.         elif type(incdirs) in (ListType, TupleType):
  275.             if not self.include_dirs:
  276.                 pass
  277.             incdirs = list(incdirs) + []
  278.         else:
  279.             raise TypeError, "'include_dirs' (if supplied) must be a list of strings"
  280.         if macros is None is None is None:
  281.             extra = []
  282.         
  283.         objects = self.object_filenames(sources, strip_dir = 0, output_dir = outdir)
  284.         if not len(objects) == len(sources):
  285.             raise AssertionError
  286.         if self.force:
  287.             skip_source = { }
  288.             for source in sources:
  289.                 skip_source[source] = 0
  290.             
  291.         elif depends is None:
  292.             skip_source = { }
  293.             for source in sources:
  294.                 skip_source[source] = 1
  295.             
  296.             (n_sources, n_objects) = newer_pairwise(sources, objects)
  297.             for source in n_sources:
  298.                 skip_source[source] = 0
  299.             
  300.         else:
  301.             skip_source = { }
  302.             L = depends[:] + [
  303.                 None]
  304.             for i in range(len(objects)):
  305.                 source = sources[i]
  306.                 L[-1] = source
  307.                 if newer_group(L, objects[i]):
  308.                     skip_source[source] = 0
  309.                     continue
  310.                 skip_source[source] = 1
  311.             
  312.         pp_opts = gen_preprocess_options(macros, incdirs)
  313.         build = { }
  314.         for i in range(len(sources)):
  315.             src = sources[i]
  316.             obj = objects[i]
  317.             ext = os.path.splitext(src)[1]
  318.             self.mkpath(os.path.dirname(obj))
  319.             if skip_source[src]:
  320.                 log.debug('skipping %s (%s up-to-date)', src, obj)
  321.                 continue
  322.             build[obj] = (src, ext)
  323.         
  324.         return (macros, objects, extra, pp_opts, build)
  325.  
  326.     
  327.     def _get_cc_args(self, pp_opts, debug, before):
  328.         cc_args = pp_opts + [
  329.             '-c']
  330.         if debug:
  331.             cc_args[:0] = [
  332.                 '-g']
  333.         
  334.         if before:
  335.             cc_args[:0] = before
  336.         
  337.         return cc_args
  338.  
  339.     
  340.     def _fix_compile_args(self, output_dir, macros, include_dirs):
  341.         """Typecheck and fix-up some of the arguments to the 'compile()'
  342.         method, and return fixed-up values.  Specifically: if 'output_dir'
  343.         is None, replaces it with 'self.output_dir'; ensures that 'macros'
  344.         is a list, and augments it with 'self.macros'; ensures that
  345.         'include_dirs' is a list, and augments it with 'self.include_dirs'.
  346.         Guarantees that the returned values are of the correct type,
  347.         i.e. for 'output_dir' either string or None, and for 'macros' and
  348.         'include_dirs' either list or None.
  349.         """
  350.         if output_dir is None:
  351.             output_dir = self.output_dir
  352.         elif type(output_dir) is not StringType:
  353.             raise TypeError, "'output_dir' must be a string or None"
  354.         
  355.         if macros is None:
  356.             macros = self.macros
  357.         elif type(macros) is ListType:
  358.             if not self.macros:
  359.                 pass
  360.             macros = macros + []
  361.         else:
  362.             raise TypeError, "'macros' (if supplied) must be a list of tuples"
  363.         if macros is None is None:
  364.             include_dirs = self.include_dirs
  365.         elif type(include_dirs) in (ListType, TupleType):
  366.             if not self.include_dirs:
  367.                 pass
  368.             include_dirs = list(include_dirs) + []
  369.         else:
  370.             raise TypeError, "'include_dirs' (if supplied) must be a list of strings"
  371.         return (macros is None is None, macros, include_dirs)
  372.  
  373.     
  374.     def _prep_compile(self, sources, output_dir, depends = None):
  375.         """Decide which souce files must be recompiled.
  376.  
  377.         Determine the list of object files corresponding to 'sources',
  378.         and figure out which ones really need to be recompiled.
  379.         Return a list of all object files and a dictionary telling
  380.         which source files can be skipped.
  381.         """
  382.         objects = self.object_filenames(sources, output_dir = output_dir)
  383.         if not len(objects) == len(sources):
  384.             raise AssertionError
  385.         if self.force:
  386.             skip_source = { }
  387.             for source in sources:
  388.                 skip_source[source] = 0
  389.             
  390.         elif depends is None:
  391.             skip_source = { }
  392.             for source in sources:
  393.                 skip_source[source] = 1
  394.             
  395.             (n_sources, n_objects) = newer_pairwise(sources, objects)
  396.             for source in n_sources:
  397.                 skip_source[source] = 0
  398.             
  399.         else:
  400.             skip_source = { }
  401.             L = depends[:] + [
  402.                 None]
  403.             for i in range(len(objects)):
  404.                 source = sources[i]
  405.                 L[-1] = source
  406.                 if newer_group(L, objects[i]):
  407.                     skip_source[source] = 0
  408.                     continue
  409.                 skip_source[source] = 1
  410.             
  411.         return (objects, skip_source)
  412.  
  413.     
  414.     def _fix_object_args(self, objects, output_dir):
  415.         """Typecheck and fix up some arguments supplied to various methods.
  416.         Specifically: ensure that 'objects' is a list; if output_dir is
  417.         None, replace with self.output_dir.  Return fixed versions of
  418.         'objects' and 'output_dir'.
  419.         """
  420.         if type(objects) not in (ListType, TupleType):
  421.             raise TypeError, "'objects' must be a list or tuple of strings"
  422.         type(objects) not in (ListType, TupleType)
  423.         objects = list(objects)
  424.         if output_dir is None:
  425.             output_dir = self.output_dir
  426.         elif type(output_dir) is not StringType:
  427.             raise TypeError, "'output_dir' must be a string or None"
  428.         
  429.         return (objects, output_dir)
  430.  
  431.     
  432.     def _fix_lib_args(self, libraries, library_dirs, runtime_library_dirs):
  433.         """Typecheck and fix up some of the arguments supplied to the
  434.         'link_*' methods.  Specifically: ensure that all arguments are
  435.         lists, and augment them with their permanent versions
  436.         (eg. 'self.libraries' augments 'libraries').  Return a tuple with
  437.         fixed versions of all arguments.
  438.         """
  439.         if libraries is None:
  440.             libraries = self.libraries
  441.         elif type(libraries) in (ListType, TupleType):
  442.             if not self.libraries:
  443.                 pass
  444.             libraries = list(libraries) + []
  445.         else:
  446.             raise TypeError, "'libraries' (if supplied) must be a list of strings"
  447.         if libraries is None is None:
  448.             library_dirs = self.library_dirs
  449.         elif type(library_dirs) in (ListType, TupleType):
  450.             if not self.library_dirs:
  451.                 pass
  452.             library_dirs = list(library_dirs) + []
  453.         else:
  454.             raise TypeError, "'library_dirs' (if supplied) must be a list of strings"
  455.         if libraries is None is None is None:
  456.             runtime_library_dirs = self.runtime_library_dirs
  457.         elif type(runtime_library_dirs) in (ListType, TupleType):
  458.             if not self.runtime_library_dirs:
  459.                 pass
  460.             runtime_library_dirs = list(runtime_library_dirs) + []
  461.         else:
  462.             raise TypeError, "'runtime_library_dirs' (if supplied) " + 'must be a list of strings'
  463.         return (libraries is None is None is None, library_dirs, runtime_library_dirs)
  464.  
  465.     
  466.     def _need_link(self, objects, output_file):
  467.         """Return true if we need to relink the files listed in 'objects'
  468.         to recreate 'output_file'.
  469.         """
  470.         if self.force:
  471.             return 1
  472.         if self.dry_run:
  473.             newer = newer_group(objects, output_file, missing = 'newer')
  474.         else:
  475.             newer = newer_group(objects, output_file)
  476.         return newer
  477.  
  478.     
  479.     def detect_language(self, sources):
  480.         '''Detect the language of a given file, or list of files. Uses
  481.         language_map, and language_order to do the job.
  482.         '''
  483.         if type(sources) is not ListType:
  484.             sources = [
  485.                 sources]
  486.         
  487.         lang = None
  488.         index = len(self.language_order)
  489.         for source in sources:
  490.             (base, ext) = os.path.splitext(source)
  491.             extlang = self.language_map.get(ext)
  492.             
  493.             try:
  494.                 extindex = self.language_order.index(extlang)
  495.                 if extindex < index:
  496.                     lang = extlang
  497.                     index = extindex
  498.             continue
  499.             except ValueError:
  500.                 continue
  501.             
  502.  
  503.         
  504.         return lang
  505.  
  506.     
  507.     def preprocess(self, source, output_file = None, macros = None, include_dirs = None, extra_preargs = None, extra_postargs = None):
  508.         """Preprocess a single C/C++ source file, named in 'source'.
  509.         Output will be written to file named 'output_file', or stdout if
  510.         'output_file' not supplied.  'macros' is a list of macro
  511.         definitions as for 'compile()', which will augment the macros set
  512.         with 'define_macro()' and 'undefine_macro()'.  'include_dirs' is a
  513.         list of directory names that will be added to the default list.
  514.  
  515.         Raises PreprocessError on failure.
  516.         """
  517.         pass
  518.  
  519.     
  520.     def compile(self, sources, output_dir = None, macros = None, include_dirs = None, debug = 0, extra_preargs = None, extra_postargs = None, depends = None):
  521.         '''Compile one or more source files.
  522.  
  523.         \'sources\' must be a list of filenames, most likely C/C++
  524.         files, but in reality anything that can be handled by a
  525.         particular compiler and compiler class (eg. MSVCCompiler can
  526.         handle resource files in \'sources\').  Return a list of object
  527.         filenames, one per source filename in \'sources\'.  Depending on
  528.         the implementation, not all source files will necessarily be
  529.         compiled, but all corresponding object filenames will be
  530.         returned.
  531.  
  532.         If \'output_dir\' is given, object files will be put under it, while
  533.         retaining their original path component.  That is, "foo/bar.c"
  534.         normally compiles to "foo/bar.o" (for a Unix implementation); if
  535.         \'output_dir\' is "build", then it would compile to
  536.         "build/foo/bar.o".
  537.  
  538.         \'macros\', if given, must be a list of macro definitions.  A macro
  539.         definition is either a (name, value) 2-tuple or a (name,) 1-tuple.
  540.         The former defines a macro; if the value is None, the macro is
  541.         defined without an explicit value.  The 1-tuple case undefines a
  542.         macro.  Later definitions/redefinitions/ undefinitions take
  543.         precedence.
  544.  
  545.         \'include_dirs\', if given, must be a list of strings, the
  546.         directories to add to the default include file search path for this
  547.         compilation only.
  548.  
  549.         \'debug\' is a boolean; if true, the compiler will be instructed to
  550.         output debug symbols in (or alongside) the object file(s).
  551.  
  552.         \'extra_preargs\' and \'extra_postargs\' are implementation- dependent.
  553.         On platforms that have the notion of a command-line (e.g. Unix,
  554.         DOS/Windows), they are most likely lists of strings: extra
  555.         command-line arguments to prepand/append to the compiler command
  556.         line.  On other platforms, consult the implementation class
  557.         documentation.  In any event, they are intended as an escape hatch
  558.         for those occasions when the abstract compiler framework doesn\'t
  559.         cut the mustard.
  560.  
  561.         \'depends\', if given, is a list of filenames that all targets
  562.         depend on.  If a source file is older than any file in
  563.         depends, then the source file will be recompiled.  This
  564.         supports dependency tracking, but only at a coarse
  565.         granularity.
  566.  
  567.         Raises CompileError on failure.
  568.         '''
  569.         (macros, objects, extra_postargs, pp_opts, build) = self._setup_compile(output_dir, macros, include_dirs, sources, depends, extra_postargs)
  570.         cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)
  571.         for obj in objects:
  572.             
  573.             try:
  574.                 (src, ext) = build[obj]
  575.             except KeyError:
  576.                 continue
  577.  
  578.             self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
  579.         
  580.         return objects
  581.  
  582.     
  583.     def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
  584.         """Compile 'src' to product 'obj'."""
  585.         pass
  586.  
  587.     
  588.     def create_static_lib(self, objects, output_libname, output_dir = None, debug = 0, target_lang = None):
  589.         '''Link a bunch of stuff together to create a static library file.
  590.         The "bunch of stuff" consists of the list of object files supplied
  591.         as \'objects\', the extra object files supplied to
  592.         \'add_link_object()\' and/or \'set_link_objects()\', the libraries
  593.         supplied to \'add_library()\' and/or \'set_libraries()\', and the
  594.         libraries supplied as \'libraries\' (if any).
  595.  
  596.         \'output_libname\' should be a library name, not a filename; the
  597.         filename will be inferred from the library name.  \'output_dir\' is
  598.         the directory where the library file will be put.
  599.  
  600.         \'debug\' is a boolean; if true, debugging information will be
  601.         included in the library (note that on most platforms, it is the
  602.         compile step where this matters: the \'debug\' flag is included here
  603.         just for consistency).
  604.  
  605.         \'target_lang\' is the target language for which the given objects
  606.         are being compiled. This allows specific linkage time treatment of
  607.         certain languages.
  608.  
  609.         Raises LibError on failure.
  610.         '''
  611.         pass
  612.  
  613.     SHARED_OBJECT = 'shared_object'
  614.     SHARED_LIBRARY = 'shared_library'
  615.     EXECUTABLE = 'executable'
  616.     
  617.     def link(self, target_desc, objects, output_filename, output_dir = None, libraries = None, library_dirs = None, runtime_library_dirs = None, export_symbols = None, debug = 0, extra_preargs = None, extra_postargs = None, build_temp = None, target_lang = None):
  618.         '''Link a bunch of stuff together to create an executable or
  619.         shared library file.
  620.  
  621.         The "bunch of stuff" consists of the list of object files supplied
  622.         as \'objects\'.  \'output_filename\' should be a filename.  If
  623.         \'output_dir\' is supplied, \'output_filename\' is relative to it
  624.         (i.e. \'output_filename\' can provide directory components if
  625.         needed).
  626.  
  627.         \'libraries\' is a list of libraries to link against.  These are
  628.         library names, not filenames, since they\'re translated into
  629.         filenames in a platform-specific way (eg. "foo" becomes "libfoo.a"
  630.         on Unix and "foo.lib" on DOS/Windows).  However, they can include a
  631.         directory component, which means the linker will look in that
  632.         specific directory rather than searching all the normal locations.
  633.  
  634.         \'library_dirs\', if supplied, should be a list of directories to
  635.         search for libraries that were specified as bare library names
  636.         (ie. no directory component).  These are on top of the system
  637.         default and those supplied to \'add_library_dir()\' and/or
  638.         \'set_library_dirs()\'.  \'runtime_library_dirs\' is a list of
  639.         directories that will be embedded into the shared library and used
  640.         to search for other shared libraries that *it* depends on at
  641.         run-time.  (This may only be relevant on Unix.)
  642.  
  643.         \'export_symbols\' is a list of symbols that the shared library will
  644.         export.  (This appears to be relevant only on Windows.)
  645.  
  646.         \'debug\' is as for \'compile()\' and \'create_static_lib()\', with the
  647.         slight distinction that it actually matters on most platforms (as
  648.         opposed to \'create_static_lib()\', which includes a \'debug\' flag
  649.         mostly for form\'s sake).
  650.  
  651.         \'extra_preargs\' and \'extra_postargs\' are as for \'compile()\' (except
  652.         of course that they supply command-line arguments for the
  653.         particular linker being used).
  654.  
  655.         \'target_lang\' is the target language for which the given objects
  656.         are being compiled. This allows specific linkage time treatment of
  657.         certain languages.
  658.  
  659.         Raises LinkError on failure.
  660.         '''
  661.         raise NotImplementedError
  662.  
  663.     
  664.     def link_shared_lib(self, objects, output_libname, output_dir = None, libraries = None, library_dirs = None, runtime_library_dirs = None, export_symbols = None, debug = 0, extra_preargs = None, extra_postargs = None, build_temp = None, target_lang = None):
  665.         self.link(CCompiler.SHARED_LIBRARY, objects, self.library_filename(output_libname, lib_type = 'shared'), output_dir, libraries, library_dirs, runtime_library_dirs, export_symbols, debug, extra_preargs, extra_postargs, build_temp, target_lang)
  666.  
  667.     
  668.     def link_shared_object(self, objects, output_filename, output_dir = None, libraries = None, library_dirs = None, runtime_library_dirs = None, export_symbols = None, debug = 0, extra_preargs = None, extra_postargs = None, build_temp = None, target_lang = None):
  669.         self.link(CCompiler.SHARED_OBJECT, objects, output_filename, output_dir, libraries, library_dirs, runtime_library_dirs, export_symbols, debug, extra_preargs, extra_postargs, build_temp, target_lang)
  670.  
  671.     
  672.     def link_executable(self, objects, output_progname, output_dir = None, libraries = None, library_dirs = None, runtime_library_dirs = None, debug = 0, extra_preargs = None, extra_postargs = None, target_lang = None):
  673.         self.link(CCompiler.EXECUTABLE, objects, self.executable_filename(output_progname), output_dir, libraries, library_dirs, runtime_library_dirs, None, debug, extra_preargs, extra_postargs, None, target_lang)
  674.  
  675.     
  676.     def library_dir_option(self, dir):
  677.         """Return the compiler option to add 'dir' to the list of
  678.         directories searched for libraries.
  679.         """
  680.         raise NotImplementedError
  681.  
  682.     
  683.     def runtime_library_dir_option(self, dir):
  684.         """Return the compiler option to add 'dir' to the list of
  685.         directories searched for runtime libraries.
  686.         """
  687.         raise NotImplementedError
  688.  
  689.     
  690.     def library_option(self, lib):
  691.         """Return the compiler option to add 'dir' to the list of libraries
  692.         linked into the shared library or executable.
  693.         """
  694.         raise NotImplementedError
  695.  
  696.     
  697.     def has_function(self, funcname, includes = None, include_dirs = None, libraries = None, library_dirs = None):
  698.         '''Return a boolean indicating whether funcname is supported on
  699.         the current platform.  The optional arguments can be used to
  700.         augment the compilation environment.
  701.         '''
  702.         import tempfile as tempfile
  703.         if includes is None:
  704.             includes = []
  705.         
  706.         if include_dirs is None:
  707.             include_dirs = []
  708.         
  709.         if libraries is None:
  710.             libraries = []
  711.         
  712.         if library_dirs is None:
  713.             library_dirs = []
  714.         
  715.         (fd, fname) = tempfile.mkstemp('.c', funcname, text = True)
  716.         f = os.fdopen(fd, 'w')
  717.         for incl in includes:
  718.             f.write('#include "%s"\n' % incl)
  719.         
  720.         f.write('main (int argc, char **argv) {\n    %s();\n}\n' % funcname)
  721.         f.close()
  722.         
  723.         try:
  724.             objects = self.compile([
  725.                 fname], include_dirs = include_dirs)
  726.         except CompileError:
  727.             return False
  728.  
  729.         
  730.         try:
  731.             self.link_executable(objects, 'a.out', libraries = libraries, library_dirs = library_dirs)
  732.         except (LinkError, TypeError):
  733.             return False
  734.  
  735.         return True
  736.  
  737.     
  738.     def find_library_file(self, dirs, lib, debug = 0):
  739.         """Search the specified list of directories for a static or shared
  740.         library file 'lib' and return the full path to that file.  If
  741.         'debug' true, look for a debugging version (if that makes sense on
  742.         the current platform).  Return None if 'lib' wasn't found in any of
  743.         the specified directories.
  744.         """
  745.         raise NotImplementedError
  746.  
  747.     
  748.     def object_filenames(self, source_filenames, strip_dir = 0, output_dir = ''):
  749.         if output_dir is None:
  750.             output_dir = ''
  751.         
  752.         obj_names = []
  753.         for src_name in source_filenames:
  754.             (base, ext) = os.path.splitext(src_name)
  755.             base = os.path.splitdrive(base)[1]
  756.             base = base[os.path.isabs(base):]
  757.             if ext not in self.src_extensions:
  758.                 raise UnknownFileError, "unknown file type '%s' (from '%s')" % (ext, src_name)
  759.             ext not in self.src_extensions
  760.             if strip_dir:
  761.                 base = os.path.basename(base)
  762.             
  763.             obj_names.append(os.path.join(output_dir, base + self.obj_extension))
  764.         
  765.         return obj_names
  766.  
  767.     
  768.     def shared_object_filename(self, basename, strip_dir = 0, output_dir = ''):
  769.         if not output_dir is not None:
  770.             raise AssertionError
  771.         if strip_dir:
  772.             basename = os.path.basename(basename)
  773.         
  774.         return os.path.join(output_dir, basename + self.shared_lib_extension)
  775.  
  776.     
  777.     def executable_filename(self, basename, strip_dir = 0, output_dir = ''):
  778.         if not output_dir is not None:
  779.             raise AssertionError
  780.         if strip_dir:
  781.             basename = os.path.basename(basename)
  782.         
  783.         if not self.exe_extension:
  784.             pass
  785.         return os.path.join(output_dir, basename + '')
  786.  
  787.     
  788.     def library_filename(self, libname, lib_type = 'static', strip_dir = 0, output_dir = ''):
  789.         if not output_dir is not None:
  790.             raise AssertionError
  791.         if lib_type not in ('static', 'shared', 'dylib'):
  792.             raise ValueError, '\'lib_type\' must be "static", "shared" or "dylib"'
  793.         lib_type not in ('static', 'shared', 'dylib')
  794.         fmt = getattr(self, lib_type + '_lib_format')
  795.         ext = getattr(self, lib_type + '_lib_extension')
  796.         (dir, base) = os.path.split(libname)
  797.         filename = fmt % (base, ext)
  798.         if strip_dir:
  799.             dir = ''
  800.         
  801.         return os.path.join(output_dir, dir, filename)
  802.  
  803.     
  804.     def announce(self, msg, level = 1):
  805.         log.debug(msg)
  806.  
  807.     
  808.     def debug_print(self, msg):
  809.         DEBUG = DEBUG
  810.         import distutils.debug
  811.         if DEBUG:
  812.             print msg
  813.         
  814.  
  815.     
  816.     def warn(self, msg):
  817.         sys.stderr.write('warning: %s\n' % msg)
  818.  
  819.     
  820.     def execute(self, func, args, msg = None, level = 1):
  821.         execute(func, args, msg, self.dry_run)
  822.  
  823.     
  824.     def spawn(self, cmd):
  825.         spawn(cmd, dry_run = self.dry_run)
  826.  
  827.     
  828.     def move_file(self, src, dst):
  829.         return move_file(src, dst, dry_run = self.dry_run)
  830.  
  831.     
  832.     def mkpath(self, name, mode = 511):
  833.         mkpath(name, mode, dry_run = self.dry_run)
  834.  
  835.  
  836. _default_compilers = (('cygwin.*', 'unix'), ('os2emx', 'emx'), ('posix', 'unix'), ('nt', 'msvc'), ('mac', 'mwerks'))
  837.  
  838. def get_default_compiler(osname = None, platform = None):
  839.     ''' Determine the default compiler to use for the given platform.
  840.  
  841.         osname should be one of the standard Python OS names (i.e. the
  842.         ones returned by os.name) and platform the common value
  843.         returned by sys.platform for the platform in question.
  844.  
  845.         The default values are os.name and sys.platform in case the
  846.         parameters are not given.
  847.  
  848.     '''
  849.     if osname is None:
  850.         osname = os.name
  851.     
  852.     if platform is None:
  853.         platform = sys.platform
  854.     
  855.     for pattern, compiler in _default_compilers:
  856.         if re.match(pattern, platform) is not None or re.match(pattern, osname) is not None:
  857.             return compiler
  858.     
  859.     return 'unix'
  860.  
  861. compiler_class = {
  862.     'unix': ('unixccompiler', 'UnixCCompiler', 'standard UNIX-style compiler'),
  863.     'msvc': ('msvccompiler', 'MSVCCompiler', 'Microsoft Visual C++'),
  864.     'cygwin': ('cygwinccompiler', 'CygwinCCompiler', 'Cygwin port of GNU C Compiler for Win32'),
  865.     'mingw32': ('cygwinccompiler', 'Mingw32CCompiler', 'Mingw32 port of GNU C Compiler for Win32'),
  866.     'bcpp': ('bcppcompiler', 'BCPPCompiler', 'Borland C++ Compiler'),
  867.     'mwerks': ('mwerkscompiler', 'MWerksCompiler', 'MetroWerks CodeWarrior'),
  868.     'emx': ('emxccompiler', 'EMXCCompiler', 'EMX port of GNU C Compiler for OS/2') }
  869.  
  870. def show_compilers():
  871.     '''Print list of available compilers (used by the "--help-compiler"
  872.     options to "build", "build_ext", "build_clib").
  873.     '''
  874.     FancyGetopt = FancyGetopt
  875.     import distutils.fancy_getopt
  876.     compilers = []
  877.     for compiler in compiler_class.keys():
  878.         compilers.append(('compiler=' + compiler, None, compiler_class[compiler][2]))
  879.     
  880.     compilers.sort()
  881.     pretty_printer = FancyGetopt(compilers)
  882.     pretty_printer.print_help('List of available compilers:')
  883.  
  884.  
  885. def new_compiler(plat = None, compiler = None, verbose = 0, dry_run = 0, force = 0):
  886.     '''Generate an instance of some CCompiler subclass for the supplied
  887.     platform/compiler combination.  \'plat\' defaults to \'os.name\'
  888.     (eg. \'posix\', \'nt\'), and \'compiler\' defaults to the default compiler
  889.     for that platform.  Currently only \'posix\' and \'nt\' are supported, and
  890.     the default compilers are "traditional Unix interface" (UnixCCompiler
  891.     class) and Visual C++ (MSVCCompiler class).  Note that it\'s perfectly
  892.     possible to ask for a Unix compiler object under Windows, and a
  893.     Microsoft compiler object under Unix -- if you supply a value for
  894.     \'compiler\', \'plat\' is ignored.
  895.     '''
  896.     if plat is None:
  897.         plat = os.name
  898.     
  899.     
  900.     try:
  901.         if compiler is None:
  902.             compiler = get_default_compiler(plat)
  903.         
  904.         (module_name, class_name, long_description) = compiler_class[compiler]
  905.     except KeyError:
  906.         msg = "don't know how to compile C/C++ code on platform '%s'" % plat
  907.         if compiler is not None:
  908.             msg = msg + " with '%s' compiler" % compiler
  909.         
  910.         raise DistutilsPlatformError, msg
  911.  
  912.     
  913.     try:
  914.         module_name = 'distutils.' + module_name
  915.         __import__(module_name)
  916.         module = sys.modules[module_name]
  917.         klass = vars(module)[class_name]
  918.     except ImportError:
  919.         raise DistutilsModuleError, "can't compile C/C++ code: unable to load module '%s'" % module_name
  920.     except KeyError:
  921.         raise DistutilsModuleError, ("can't compile C/C++ code: unable to find class '%s' " + "in module '%s'") % (class_name, module_name)
  922.  
  923.     return klass(None, dry_run, force)
  924.  
  925.  
  926. def gen_preprocess_options(macros, include_dirs):
  927.     """Generate C pre-processor options (-D, -U, -I) as used by at least
  928.     two types of compilers: the typical Unix compiler and Visual C++.
  929.     'macros' is the usual thing, a list of 1- or 2-tuples, where (name,)
  930.     means undefine (-U) macro 'name', and (name,value) means define (-D)
  931.     macro 'name' to 'value'.  'include_dirs' is just a list of directory
  932.     names to be added to the header file search path (-I).  Returns a list
  933.     of command-line options suitable for either Unix compilers or Visual
  934.     C++.
  935.     """
  936.     pp_opts = []
  937.     for macro in macros:
  938.         None if type(macro) is TupleType else 1
  939.         if len(macro) == 2:
  940.             if macro[1] is None:
  941.                 pp_opts.append('-D%s' % macro[0])
  942.             else:
  943.                 pp_opts.append('-D%s=%s' % macro)
  944.         macro[1] is None
  945.     
  946.     for dir in include_dirs:
  947.         pp_opts.append('-I%s' % dir)
  948.     
  949.     return pp_opts
  950.  
  951.  
  952. def gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries):
  953.     """Generate linker options for searching library directories and
  954.     linking with specific libraries.  'libraries' and 'library_dirs' are,
  955.     respectively, lists of library names (not filenames!) and search
  956.     directories.  Returns a list of command-line options suitable for use
  957.     with some compiler (depending on the two format strings passed in).
  958.     """
  959.     lib_opts = []
  960.     for dir in library_dirs:
  961.         lib_opts.append(compiler.library_dir_option(dir))
  962.     
  963.     for dir in runtime_library_dirs:
  964.         opt = compiler.runtime_library_dir_option(dir)
  965.         if type(opt) is ListType:
  966.             lib_opts = lib_opts + opt
  967.             continue
  968.         lib_opts.append(opt)
  969.     
  970.     for lib in libraries:
  971.         (lib_dir, lib_name) = os.path.split(lib)
  972.         if lib_dir:
  973.             lib_file = compiler.find_library_file([
  974.                 lib_dir], lib_name)
  975.             if lib_file:
  976.                 lib_opts.append(lib_file)
  977.             else:
  978.                 compiler.warn("no library file corresponding to '%s' found (skipping)" % lib)
  979.         lib_file
  980.         lib_opts.append(compiler.library_option(lib))
  981.     
  982.     return lib_opts
  983.  
  984.